// 1.引入vue
import Vue from 'vue'
//2.引入vuex
import Vuex from 'vuex'
//引入axios
import axios from 'axios'

//3.使用vuex(vuex本质上是插件,需要使用)
Vue.use(Vuex)

//创建state
const state = {
  count: 0,
  movieList: []
}
//修改state
const mutations = {
  increment(state) {
    state.count++
  },
  decrement(state) {
    state.count--
  },
  incrementN(state, { n }) {
    state.count += n
  },
  setMovieList(state, payload) {
    state.movieList = payload
  }
}
//getters
const getters = {
  myMovieList(state) {
    return state.movieList.filter(item => {
      return item.albumName.length < 5
    })
  },
  yourMovieList(state) {
    return ({ m, n }) => {
      return state.movieList.filter(item => {
        return item.albumName.length > m && item.albumName.length < n
      })
    }
  }
}

//书写异步
const actions = {
  //英文actions中一定会调用commit去调用mutations,所以actions中的函数接受一个对象(context,可以从中解构出来commit),对象提供一个commit方法
  incrementWait({ commit }) {
    setTimeout(() => {
      //actions中不操作数据,异步完成后把数据交给mutation去操作数据
      commit('increment')
    }, 2000)
  },
  incrementNWait({ commit }, payload) {
    setTimeout(() => {
      commit('incrementN', payload)
    }, 2000)
  },
  async getMovieList({ commit }) {
    const result = await axios.get('https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=2&ret_num=48&session=b9fd987164f6aa47fad266f57dffaa6a')
    commit('setMovieList', result.data.data.list)
  }


}


//4.暴露store
export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})